import os
import logging

from django.forms import ValidationError
def get_files_from_request(request):
  files = []
  if len(request.FILES):
    for _, file in request.FILES.items():
      files.append(file)

  return files


def generate_file_stream(file_path):
  with open(file_path, "rb") as f:
          while True:
              c=f.read(1024 * 1024 * 512)
              if c:
                  yield c
              else:
                  break
              



B = 1
KB = B << 10
MB = KB << 10
GB = MB << 10
TB = GB << 10
EB = TB << 10

B_STR = 'B'
KB_STR = 'KB'
MB_STR = 'MB'
GB_STR = 'GB'
TB_STR = 'TB'
EB_STR = 'EB'


def file_size_convert(file_size, is_round=False, point_count=2):
    """
    @param file_size : int :文件大小 Byte 单位 eg: 1024
    @param is_round: bool :是否四舍五入
    @param point_count: int: 保留几位小数
    @return: convert_result: str:  转化后结果 0.9MB , ok : bool: 是否转换成功
    """
    
    ok = False

    try:
        real_int_size = float(file_size)
    except Exception:
        return file_size, ok
    if file_size <= 0:
        return file_size, ok

    ok = True

    size_group_list = [(B, B_STR), (KB, KB_STR), (MB, MB_STR),
                       (GB, GB_STR), (TB, TB_STR)]
    size_name = B_STR
    size_unit = B
    for size in size_group_list:
        size_unit, size_name = size

        if real_int_size / size_unit < 1024:
            break

    real_int_size /= size_unit

    if not is_round:
        real_int_size = str(real_int_size).split(
            '.')[0] + '.' + str(real_int_size).split('.')[1][:2]
    else:
        real_int_size = round(real_int_size, point_count)

    convert_result = str(real_int_size) + size_name

    if int(float(real_int_size)) == 0:
        return str(file_size) + B_STR, True

    return convert_result, ok


def get_file_format(filename):
    file_split = filename.split(".")
    return file_split[len(file_split) - 1]
